package com.zoho.daliansheng.common;

import com.alibaba.fastjson.JSONObject;
import com.zoho.daliansheng.utils.HttpUtil;
import com.zoho.daliansheng.utils.SslUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.HashMap;

@Component
public class U8SystemRecord {

    @Value("${u8System.fromAccount}")
    private String fromAccount;

    @Value("${u8System.appKey}")
    private String appKey;
    @Value("${u8System.toAccount}")
    private String toAccount;
    @Value("${u8System.appSecret}")
    private String appSecret;

    public String getFromAccount() {
        return fromAccount;
    }

    public String getAppKey() {
        return appKey;
    }

    public String getToAccount() {
        return toAccount;
    }

    public String getAppSecret() {
        return appSecret;
    }

    public String getAccessToken() {
        U8SystemTokenVo tokenVo = U8SystemTokenVo.getInstance();
        Long expireTime = tokenVo.getExpireTime();
        String token = "";
        if (expireTime + 600000 > System.currentTimeMillis()) {
            // 还未过期
            token = tokenVo.getAccessToken();
        } else {
            token = this.getAccessTokenByRefreshToken();
            U8SystemTokenVo.setInstance(System.currentTimeMillis(), token);
        }
        return token;
    }


    private String getAccessTokenByRefreshToken() {
        String url = "https://api.yonyouup.com/system/token?from_account=" + fromAccount + "&app_key=" + appKey + "&app_secret=" + appSecret;
        URL restURL = null;
        try {
            restURL = new URL(url);
            // PrintWriter out = null;
            //忽略HTTPS请求的SSL证书，必须在openConnection之前调用
            if ("https".equalsIgnoreCase(restURL.getProtocol())) {
                SslUtil.ignoreSsl();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONObject jsonObject = HttpUtil.getData(url, new HashMap<>());
        return jsonObject.getJSONObject("token").getString("id");
    }

}
